package org.jeecg.modules.activiti.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.task.Task;
import org.jeecg.modules.activiti.service.SimpleTaskService;
import org.jeecg.modules.activiti.util.ActUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/act/demo")
@Slf4j
public class DemoController {
    public static String processInstanceId = "1";
    @Autowired
    SimpleTaskService simpleTaskService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ManagementService managementService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private RuntimeService runtimeService;

    @GetMapping("/getTask")
    public String getTask(@RequestParam int pi, @RequestParam int ps) {
        JSONArray list = new JSONArray();
        for (Task task : taskService.createTaskQuery().processDefinitionKey("loanProcess").listPage((pi - 1) * ps, pi * ps)) {
            JSONObject item = new JSONObject();
            item.put("name", task.getName());
            item.put("id", task.getId());
            item.putAll(JSONObject.parseObject(String.valueOf(taskService.getVariable(task.getId(), "form"))));
            list.add(item);
        }
        JSONObject resp = new JSONObject();
        resp.put("list", list);
        resp.put("total", list.size());
        return resp.toJSONString();
    }

    @PostMapping("/startTask")
    public String startTask(@RequestBody Map variables) {
        processInstanceId = simpleTaskService.startProcess(variables);
        return processInstanceId;
    }

    @PostMapping("/goAppr")
    public String goAppr(@RequestBody JSONObject req) {
        String appr = req.getString("appr");
        String id = req.getString("id");
        String gobackId = req.getString("gobackId");
        if ("1".equals(appr)) {
            taskService.complete(id, req);
        } else if ("2".equals(appr)) {
            simpleTaskService.jump2TargetFlowNode(id, "endevent1");
        } else if ("3".equals(appr)) {
            if (gobackId != null) {
                simpleTaskService.jump2TargetFlowNode(id, gobackId);
            }
        }
        return processInstanceId;
    }


    @GetMapping(path = "/getImage", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getImage(@RequestParam String id)  {
        String processInstanceId = taskService.createTaskQuery().taskId(id).singleResult().getProcessInstanceId();
        return ActUtils.getFlowImgByInstanceIdToByte(processInstanceId);
    }
}
